package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;

import cn.com.dstz.agent.config.CategoryConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.PinYinUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 品种管理Action
 * @author 叶装装
 * 
 * 2013-5-22 22:09 修复
 * 2013 -06-04 20:37 二次修复
 * 
 */
public class CategoryAct extends BaseAction{
	
	public void list( ){
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		String sql = "select c.name as name, c.id as id, c.pinyin as pinyin, c.aid as aid, a.name as agentname, c.adminid as adminid from dstzcategory c left outer join dstzagent a on c.aid = a.id where 1=1";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		
		// 这个是按参数传递的, 
		// 客户端以POST方法提交，即
		String q = getParameter( "term");
		if( StringUtils.isNotBlank( q )){
			q = decodeString( q, "UTF-8" );
			sql += " and ( c.pinyin like :pinyin or c.name like:name)";
			valueMap.put( "pinyin", "%" + q + "%" );
			valueMap.put( "name", "%" + q + "%" );
		}
		
		if( level > 0 ){
			CategoryConfig config = new CategoryConfig( admin, this.countManagerGroup( ));
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
		}
		
		Map< String, Type > aliasMap = DataBaseUtils.getAlias( new String[]{
				"name", "id" ,"pinyin", "aid", "agentname",  "adminid"
		}, new Type[]{
				Hibernate.STRING, Hibernate.INTEGER, Hibernate.STRING, Hibernate.INTEGER, Hibernate.STRING, Hibernate.INTEGER
		} );
		
		if( StringUtils.isNotBlank( q )){
			List<Map< String, Object>> list = baseService.queryList( sql, 0, 10, valueMap, aliasMap );
			
			this.ajaxResponse( JSONArray.fromObject( list ) );
			
			return;
		}
		
		
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  null,  aliasMap )  );
	
	}
	
	public String toadd( ){
		return "add";
	}
	
	public void add( ){
		int validSaveOrUpdate = validSaveOrUpdate( 0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		
		int save = baseService.save( "dstzcategory", DataBaseUtils.getData( new String[]{
				"name", "aid", "pinyin", "adminid"
		}, new Object[]{
				name, admin.get( "topaid" ), PinYinUtils.getPinYinWithOutDuoyin( name ), admin.get( "id" )
		} ) );
		this.addLog( save, "category", 0, name );
		this.ajaxResponse( save > 0 ? 0 : -1 );
		
	}
	
	public String toedit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		if( validSaveOrUpdate > 0 ){
			alertMsg( null );
			return "edit";
		}
		String sql = "select * from dstzcategory where id=:id";
		
		Map< String, Object > data = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, id ) );
		
		if( data == null || data.isEmpty( ) ){
			alertMsg( null );
			return "edit";
		}
		
		getRequest( ).setAttribute( "data", data );
		
		return "edit";
	}
	
	public void edit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		int update = baseService.update( "dstzcategory", DataBaseUtils.getData( new String[]{
				"name", "pinyin"
		}, new Object[]{
				name, StringUtils.isBlank( pinyin ) ? PinYinUtils.getPinYinWithOutDuoyin( name ) : pinyin
		} ), DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} ) );
		
		this.addLog( update, "category", 1, "ID：" + id );
		this.ajaxResponse( update > 0 ? 0 : -1 );
	}
	
	public void delete( ){
		
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						String deleteSql = "delete from dstzcategory where id =" + id;
						if( level > 0 ){
							deleteSql += " and adminid = " + admin.get( "id" );
						}
						
						updateSqlList.add( deleteSql );
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "category", 2, ids );
				
			}
		}
		
	}
	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		if( saveOrUpdate == 2 || saveOrUpdate == 1 ){
			if( id == null || id == 0 ){
				return 3;
			}
			if( saveOrUpdate == 2 ){
				return 0;
			}
		}
		
		if( ValidUtils.validLength( name, 1, 40 )){
			return 1;
		}
		
		if( ValidUtils.validLengthCanEmpty( pinyin, 255 )){
			return 4;
		}
		
		int count = 0 ;
		if( saveOrUpdate == 0 ){
			count = dbValid( );
		}else{
			if(! StringUtils.equals( name, oldname )){
				count = dbValid( );
			}
		}
		
		if( count > 0 ){
			return 2;
		}
		
		return 0;
	}
	
	private int dbValid( ){
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "name", name );
		
		String SQL = "select count(*) as a from dstzcategory where name=:name ";
		if( level > 0 ){
			SQL += "and adminid=:aid";
			valueMap.put( "aid", admin.get( "id" ) );
		}
		
		return baseService.countBySQL( SQL, valueMap  );
	}
	
	private Integer id;
	private String name;
	private String oldname;
	private String pinyin;
	
	
	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	public String getName( ) {
		return name;
	}

	public void setName( String name ) {
		if( StringUtils.isNotBlank( name )){
			name = decode( name );
		}
		this.name = name;
	}

	public String getOldname( ) {
		return oldname;
	}

	public void setOldname( String oldname ) {
		if( StringUtils.isNotBlank( oldname )){
			oldname = decode( oldname );
		}
		this.oldname = oldname;
	}

	public String getPinyin( ) {
		return pinyin;
	}

	public void setPinyin( String pinyin ) {
		if( pinyin == null ){
			pinyin = "";
		}
		this.pinyin = pinyin;
	}


	private static final long serialVersionUID = 1L;

}
